import axios from 'axios'
import { Message, MessageBox } from 'element-ui'
import store from '@/store'
import { getToken, removeToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_ORIGIN_API, // 代理路径
  // baseURL: "http://localhost:8000/api/",
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000, // request timeout
})

// request interceptor
service.interceptors.request.use(
  (config) => {
    // do something before request is sent

    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['Authorization'] = getToken()
    }
    return config
  },
  (error) => {
    // do something with request error
    return Promise.reject(error)
  },
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom status
   * Here is just an user
   * You can also judge the status by HTTP Status status
   */
  (response) => {
    // 判断响应是否为二进制
    if (!response.headers['content-type'].includes('application/json')) {
      return response
    }
    // 获取请求信息
    const { data } = response
    return getError(data)
  },
  (error) => {
    // 无网络
    if (!error || !error.response) {
      Message({
        message: error.message || '网络错误!',
        type: 'error',
        duration: 5 * 1000,
        showClose: true,
      })
      return Promise.reject(error)
    }
    return getError(error.response)
  },
)

function getError(data) {
  // 成功请求
  if (data.status < 300) {
    return data
  }
  switch (data.status) {
    // token失效
    case 401:
      Message({
        message: '对不起，您的登录信息已失效，请重新登录!',
        type: 'warning',
        duration: 5 * 1000,
        showClose: true,
      })
      // 删除token
      removeToken()
      break
    // 无权限
    case 403:
      Message({
        message: '对不起您无权访问此资源!',
        type: 'error',
        duration: 5 * 1000,
        showClose: true,
      })
      // 重新获取
      store.dispatch('user/getInfo')
      break
    // 其他错误
    default:
      Message({
        message: data.message || '请求失败!',
        type: 'error',
        duration: 5 * 1000,
        showClose: true,
      })
      break
  }
  console.log('错误响应==>', data)
  return Promise.reject(new Error(data.message || '请求错误!'))
}
export default service
